package com.ruifu.common.utils;

import com.fhzncloud.cloud.common.security.service.CloudUser;
import com.ruifu.common.po.ObjectPermissionsAuthorization;
import com.ruifu.common.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lcq
 * @create 2020/4/16
 */
@Slf4j
public class FindPermissionCommon {
    /**
     * 权限计算引擎
     * @param cloudUser 用户信息
     * @param commonPermissionObject  资源对象
     * @param objectPermissionsList   规则定义列表
     * @return
     */
    public static String findPermissionByUserIdAndPtId(CloudUser cloudUser,
                                                       CommonPermissionObject commonPermissionObject,
                                                       List<ObjectPermissionsAuthorization> objectPermissionsList) {
        String permissionCode = "";
        List<String> permissionToMeetList = new ArrayList<>();
        //构建用户信息
        UserVO userVO = new UserVO();
        userVO.setId(cloudUser.getId());
        userVO.setDeptId(cloudUser.getDeptId());
        userVO.setSecrecyLevel(Long.valueOf(cloudUser.getSecrecyLevel()));
        userVO.setTenantId(cloudUser.getTenantId());
        commonPermissionObject.setUser(userVO);

        //创建SpEL表达式的解析器
        ExpressionParser parser = new SpelExpressionParser();
        //求值上下文
        EvaluationContext context = new StandardEvaluationContext(commonPermissionObject);

        //遍历权限列表
        for (ObjectPermissionsAuthorization objectPermissionsAuthorization : objectPermissionsList) {
            log.info("Permissions:["+objectPermissionsAuthorization.getObjectCondition()+"]");
            //解析权限表达式
            Boolean objectConditionValue = (Boolean) (parser.parseExpression(objectPermissionsAuthorization.getObjectCondition()).getValue(context));

            if (objectConditionValue) {
                //存储权限二进制码
                permissionToMeetList.add(objectPermissionsAuthorization.getObjectPermissionsString());
            }
        }
        if (permissionToMeetList.size() > 0) {
            permissionCode = permissionToMeetList.get(0);
            for (int i = 1; i < permissionToMeetList.size(); i++) {
                //二进制权限字符串位运算
                permissionCode = StringOrSumOperationUtils.or2(permissionCode, permissionToMeetList.get(i));
                log.info(permissionCode);
            }
        }
        return permissionCode;
    }
}
